package cz.fimuni.pa165.backendderby.dao;

import cz.fimuni.pa165.backendderby.entities.Company;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;

/**
 *
 * @author Lukáš Slovák
 * @version 1.3
 */

@Repository
public class CompanyDAOImpl implements CompanyDAO{
    
    @PersistenceContext
    private EntityManager em;
    
    @Override
    public void create(Company company) {
        if (company != null){
            em.persist(company);
        }      
    }

    @Override
    public void remove(Company company) {
        if (company != null){           
            Company company1 = em.find(Company.class, company.getId());
            if (company1 != null){
                em.remove(company1);
            }
        }  
    }

    @Override
    public boolean update(Company company) {
        if (company != null){
            if(em.find(Company.class,company.getId())==null) {return false;}
            em.persist(em.merge(company));
            return true;
        }
        return false;
    }

    @Override
    public Company find(Long id) {
        if (id == null){
            return null;
        }
        
        Company company = em.find(Company.class, id);
        return company;
    }

    @Override
    public List<Company> findAll() {        
        Query q = em.createQuery("SELECT c FROM Company c"); 
        // musi tu byt skutocny nazov tabulky v databaze
        
        List<Company> result = q.getResultList();
        if (result.isEmpty()){
            return null;
        }else{
            return result;
        }
    }
    
}
